/*
 * @Date: 2022-02-15 17:35:34
 * @LastEditors: 春贰
 * @Desc:
 * @LastEditTime: 2023-08-28 16:53:30
 * @FilePath: \server\system\core\response\response.go
 */
package response

import (
	"io"
	"net/http"

	"github.com/gin-gonic/gin"
)

type Response struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

const (
	ERROR   = 1
	SUCCESS = 0
)

func result(code int, data interface{}, msg string, c *gin.Context) {
	dataFull := Response{
		code,
		data,
		msg,
	}
	c.JSON(http.StatusOK, dataFull)
}

func Ok(c *gin.Context) {
	result(SUCCESS, map[string]interface{}{}, "success", c)
}

func OkWithMessage(message string, c *gin.Context) {
	result(SUCCESS, map[string]interface{}{}, message, c)
}

func OkWithData(data interface{}, c *gin.Context) {
	result(SUCCESS, data, "success", c)
}

func OkWithDetailed(data interface{}, message string, c *gin.Context) {
	result(SUCCESS, data, message, c)
}

func Fail(c *gin.Context) {
	result(ERROR, map[string]interface{}{}, "error", c)
}

func FailWithMessage(message string, c *gin.Context) {
	result(ERROR, map[string]interface{}{}, message, c)
}

func FailWithDetailed(data interface{}, message string, c *gin.Context) {
	result(ERROR, data, message, c)
}

//SSEvent返回
var G_Content map[string]chan string

func SSEventSendOnce(eventtype string, message string, c *gin.Context) {
	c.Stream(func(w io.Writer) bool {
		c.SSEvent(eventtype, message)
		return false
	})
}

//do 需要给chanel写内容
func SSEventlisten(do func(chan string), c *gin.Context) {
	channel := make(chan string)
	go func() {
		defer close(channel)
		do(channel)
	}()

	c.Stream(func(w io.Writer) bool {
		if msg, ok := <-channel; ok {
			c.SSEvent("message", msg)
			return true
		}
		return false
	})
}
